package a66weding.com.jiehuntong.services;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.beans.VersionBean;
import a66weding.com.jiehuntong.common.UpdateAppController;
import a66weding.com.jiehuntong.common.UpdateConstants;
import a66weding.com.jiehuntong.common.utils.AppUtils;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.FileUtil;
import a66weding.com.jiehuntong.common.utils.MD5Util;
import a66weding.com.jiehuntong.http.RequestCode;


public class UpdateAppService extends Service  {
    private UpdateAppController updateAppController = null;
    private Notification notify;
    private NotificationManager manager;
    //是否正在下载
    private boolean isDownApp = false;
    //初次下载网络异常，没有获取到文件的长度 true 表示是这种异常，false 表示是这种异常
    private boolean isException =false;
    // 下载应用存放全路径
    private String FILE_NAME = null;
    //apk文件的大小
    private int apkLength = 0;
    //apk下载到的地方
    private int downWhile = 0;
    private VersionBean mVersionBean;
    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }
    @Override
    public void onCreate() {
        super.onCreate();
        File downloadFile = FileUtil.getDownloadFile(this);
        File apkFile=new File(downloadFile,"jiehuntong.apk");
        FILE_NAME= apkFile.getAbsolutePath();
        EventBus.getDefault().register(this);
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            Bundle bundle = intent.getExtras();
            if(bundle!=null) {
                this.mVersionBean = (VersionBean) bundle.get("version");
            }
            //网络连接上是接收到的广播
            String neReceiver = intent.getStringExtra(UpdateConstants.RECEIVER_FLAG);
            //弹出框提示更新的标志
            boolean isupdate = intent.getBooleanExtra(UpdateConstants.ACTIVITY_FLAG, false);
            //连上wifi，且在通知栏有下载状态时才启动断点下载
            if (UpdateConstants.RECEIVER_TEXT.equals(neReceiver) && isDownApp == true) {
                if(mVersionBean!=null) {
                    startDownApp(mVersionBean.getData().getApk_url());
                }
            } else if (!isDownApp && !UpdateConstants.RECEIVER_TEXT.equals(neReceiver) && !isupdate) {
            } else if (isupdate||isException==true) {
                if(mVersionBean!=null) {
                    startDownApp(mVersionBean.getData().getApk_url());
                }
            }
            intent = null;
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        /**
         *移除通知
         */
        if (manager != null) {
            manager.cancel(100);
        }
        /**
         * 清空所有handler 消息
         */
        if (completeHandler != null) {
            completeHandler.removeCallbacksAndMessages(null);
        }
    }

    // 获取更新详情
    private void getUpdateMessage() {
        if (updateAppController == null) {
            updateAppController = new UpdateAppController(this);
        }
        String path=getApplicationContext().getPackageResourcePath();
        File file = new File(path);
        String fileMD5String="";
        try{
            fileMD5String = MD5Util.getFileMD5String(file);
        }catch (Exception e){
        }
        String url= RequestCode.GET_APP_NEW_VERSION;
        updateAppController.handleGetUpdateAppByNet(url, CUtils.getVersionCode(this),fileMD5String);

    }
    @Subscribe
    public void onEventmsg(VersionBean versionbean){
        this.mVersionBean=versionbean;
    }

    /**
     * 去下载app
     */
    public void startDownApp(String path) {
        //建立下载的apk文件
        if (FILE_NAME == null) {
            Toast.makeText(UpdateAppService.this, "文件路径未找到", Toast.LENGTH_SHORT).show();
            return;
        }
        //发送通知栏
        if (manager == null && notify == null) {
            manager = (NotificationManager) this.getSystemService((this.NOTIFICATION_SERVICE));
            notify = new Notification();
            notify.icon = R.mipmap.logo;
            // 通知栏显示所用到的布局文件
            notify.contentView = new RemoteViews(this.getPackageName(),
                    R.layout.view_notify_item);
            notify.contentView.setTextViewText(
                    R.id.notify_updata_values_tv, UpdateAppService.this.getResources().getString(R.string.app_name) );
            notify.contentView.setTextColor( R.id.notify_updata_values_tv,getResources().getColor(R.color.colorMainRed));
           notify.flags=Notification.FLAG_NO_CLEAR;
            manager.notify(100, notify);
        }

        File fileInstall = new File(FILE_NAME);
        downLoadSchedule(path, completeHandler, this, fileInstall);

    }

    public void downLoadSchedule(final String uri,
                                 final Handler handler, Context context, final File file) {
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 每次读取文件的长度
        final int perLength = 4096;
        //文件大小
        new Thread() {
            @Override
            public void run() {
                super.run();
                FileOutputStream out = null;
                InputStream in = null;
                RandomAccessFile access = null;
                HttpURLConnection conn = null;
                try {
                    URL url = new URL(uri);
                    // 设置断点下载开始下载的位置单位为字节
                    if (apkLength != 0) {
                        conn = (HttpURLConnection) url.openConnection();
                        conn.setRequestProperty("Range", "bytes=" + downWhile + "-" + apkLength);
                        Thread.sleep(1000);
                        // 断点下载使用的文件对象RandomAccessFile
                        access = new RandomAccessFile(FILE_NAME, "rw");
                        // 移动指针到开始位置
                        access.seek(downWhile);
                    } else {
                        conn = (HttpURLConnection) url.openConnection();
                        //设置非断点下载流
                        out = new FileOutputStream(file);
                    }
                    conn.setDoInput(true);
                    conn.connect();
                    // 每次读取1k
                    byte[] buffer = new byte[perLength];
                    int len = -1;
                    int temp = 0;
                    //第一次下载
                    if (conn.getResponseCode() == 200) {
                        int length = apkLength = conn.getContentLength();
                        in = conn.getInputStream();
                        while ((len = in.read(buffer)) != -1) {
                            //记录下载到的地方
                            downWhile += len;
                            // 写入文件
                            out.write(buffer, 0, len);
                            // 当前进度
                            int schedule = (int) ((file.length() * 100) / length);
                            // 通知更新进度（10,7,4整除才通知，没必要每次都更新进度）
                            if (temp != schedule
                                    && (schedule % 10 == 0 || schedule % 4 == 0 || schedule % 7 == 0)) {
                                // 保证同一个数据只发了一次
                                temp = schedule;
                                UpdateAppService.this.isDownApp = true;
                                handler.sendEmptyMessage(schedule);
                            }
                        }
                        //断点续传
                    } else if (conn.getResponseCode() == 206) {
                        in = conn.getInputStream();
                        while ((len = in.read(buffer)) != -1) {
                            //记录下载到的地方
                            downWhile += len;
                            // 写入文件
                            access.write(buffer, 0, len);
                            // 当前进度
                            int schedule = (int) ((file.length() * 100) / apkLength);
                            // 通知更新进度（10,7,4整除才通知，没必要每次都更新进度）
                            if (temp != schedule
                                    && (schedule % 10 == 0 || schedule % 4 == 0 || schedule % 7 == 0)) {
                                // 保证同一个数据只发了一次
                                temp = schedule;
                                UpdateAppService.this.isDownApp = true;
                                handler.sendEmptyMessage(schedule);
                            }
                        }
                    }
                    isException=false;
                } catch (Exception e) {
                    isException=true;
                    handler.sendEmptyMessage(-1);
                    e.printStackTrace();
                } finally {
                    try {
                        out.flush();
                        out.close();
                        in.close();
                        conn.disconnect();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }



    /**
     * 更新通知栏
     */
    private Handler completeHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {

            // 更新通知栏
            if(msg.what==-1) {
                //下载失败时
                notify.contentView.setTextViewText(
                        R.id.notify_updata_values_tv, UpdateAppService.this.getResources().getString(R.string.app_name));
                notify.contentView.setTextViewText(
                        R.id.notify_updata_state, "下载失败");
                notify.contentView.setViewVisibility(R.id.notify_updata_progress, View.GONE);
                notify.contentView.setViewVisibility(R.id.notify_updata_state, View.VISIBLE);
                manager.notify(100, notify);
            }else if (msg.what < 100&&msg.what>=0) {
                notify.contentView.setTextViewText(
                        R.id.notify_updata_values_tv,"正在下载:"+ UpdateAppService.this.getResources().getString(R.string.app_name) +" " + msg.what + "%");
                notify.contentView.setProgressBar(R.id.notify_updata_progress,
                        100, msg.what, false);
                notify.contentView.setViewVisibility(R.id.notify_updata_progress,
                        View.VISIBLE);
                notify.contentView.setViewVisibility(R.id.notify_updata_state,
                        View.GONE);

                manager.notify(100, notify);
            } else {
                notify.contentView.setTextViewText(
                        R.id.notify_updata_values_tv, UpdateAppService.this.getResources().getString(R.string.updte_complete));
                notify.contentView.setProgressBar(R.id.notify_updata_progress,
                        100, msg.what, false);
                notify.contentView.setViewVisibility(R.id.notify_updata_progress,
                        View.VISIBLE);
                notify.contentView.setViewVisibility(R.id.notify_updata_state,
                        View.GONE);
                // 清除通知栏
                manager.cancel(100);
                //没有正在下载版本
                UpdateAppService.this.isDownApp = false;
                File file = new File(FILE_NAME);

                AppUtils.installApk(UpdateAppService.this, file);
                UpdateAppController.stopUpdateService(UpdateAppService.this);
            }
        }
    };
}
